<?php
namespace app\mobile\controller;

use app\model\Comm; 
use app\model\Theme; 
use app\model\Worker; 

class WOrderAgent extends Base
{
    public function W_order_agent()
    {
global $_G, $_P;
$fans = $this->checkuser();
$themeid = intval($_P['themeid']);
if($themeid < 0){
	return_msg('管理后台地址不正确');
}
$system=$_G['system'];
$theme = Theme::getThemeById($themeid);
$config = 	Theme::getConfig($themeid);
if(empty($theme['id'])){
	return_msg('管理后台地址不正确');
}
$myworker = Worker::getThemeWorkerByOpenidNew($_G['openid'],$themeid);
if(!(!$system['is_multiple_merchants'] || $config['showshop']==0 || ($system['is_multiple_merchants'] && $config['showshop']==$myworker['company']))){
	$myworker = "";
}
if (empty($myworker) || $myworker['level']!=4) {
	return_msg('您不是代理,无权访问');
}
$msg = Worker::gethoutaistats();


if (!empty($msg)) {
	return_msg($msg);
}
	$wx = $_G['platform']['jssdkconfig']; 

	$op='my';


if($config['is_comm6_agent']==0){
    $tiaojian = " and  r.workerid = " . $myworker['uid'];
}else{
    $tiaojian = " and r.fromuid = " . $_G['member']['uid'] . " and  r.workerid = " . $myworker['uid'];
}

$pageNumber = max ( 1, intval ( $_P['page'] ) );
$pageSize = 10;

if ($_P['show']!='get') {
	$gsumall = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
		left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
		WHERE r.themeid ='{$themeid}' " . $tiaojian . "" ));


	$gsum12 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
		left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
		WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and r.status!=3 " ));
	$gsum13 = intval(db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename ( t_record ) . " as r
		left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid
		WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = 0 " ));

	$gsum16 = Comm::getCommFeeSum($myworker['uid'],$themeid);
}

$id = intval($_P['id']);
if ($id > 0){
	$op='all';
	$tiaojian = " and  r.id = " . $id;
}

if ($_P['show']=='get') {
	$pageNumber = $pageNumber + 1;
}


$op2 = $_P['op2'] ;
$show = $_P['show'];
if ($system['softstyle']==5) {
	$tuanzhang = $config['jmbiemingwenzi'];
	$danmai = $config['jmbiemingwenzi2'];
}else{
	$tuanzhang = '团长';
	$danmai = '单买';	
}
$do = 'w_order_agent';

$itemheight = 3.3;
if (!empty($config['address'])){
	$itemheight = $itemheight+0.3;
}
if (!empty($config['shops'])){
	$itemheight = $itemheight+0.3;
}
if (!empty($config['datetime'])){
	$itemheight = $itemheight+0.3;

}
if (!empty($config['addinfo'])){
	$itemheight = $itemheight+0.3;

}
$scan = intval($_P['scan']);

switch ($scan) {
	case '0':
		$sql="WHERE r.themeid ='{$themeid}' ". $tiaojian;
		break;
	case '30':
		$sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.type = 0 and r.status > 0";
		break;
	case '1':
		$sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.type = 1 and r.status > 0";
		break;
	case '9':
		$sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.type = 9 and r.status > 0";
		break;
	case '10':
		$sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and r.isfinish = 0 and r.xunifinish = 0";
		break;
	case '11':
		$sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and (r.isfinish = 1 or r.xunifinish = 1)";
		break;
	case '12':
		$sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status > 0 and r.status !=3";
		break;
	case '13':
		$sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = 0 ";
		break;
	case '14':
		$sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = '-1' ";
		break;
	case '15':
		$sql="WHERE r.themeid ='{$themeid}' " . $tiaojian . " and r.status = 3 ";
		break;
	default:
		$sql="WHERE r.themeid ='{$themeid}' ". $tiaojian;
		break;
}

	//获得按扭文字
    if ($config['groupprice2']>0 || $config['groupprice3']>0) {
		$gruoptips = $config['formtextcenter2'];
		$gruoptips = str_replace("#fee",'',$gruoptips);
		$gruoptips = str_replace("#dan",'',$gruoptips);
		$gruoptips = str_replace("#tuan",'',$gruoptips);
		$gruoptips = str_replace("#br",'',$gruoptips);
		$gruoptips = str_replace("￥",'',$gruoptips);
		$gruoptips2 = $gruoptips ;

		$gruoptips = $config['formtextcenter'];
		$gruoptips = str_replace("#fee",'',$gruoptips);
		$gruoptips = str_replace("#dan",'',$gruoptips);
		$gruoptips = str_replace("#tuan",'',$gruoptips);
		$gruoptips = str_replace("#br",'',$gruoptips);
		$gruoptips = str_replace("￥",'',$gruoptips);

		if (empty($config['formtextcenter'])) {
			$gruoptips = $config['maxcountall']."人团";
		}
		if (empty($config['formtextcenter2'])) {
			$gruoptips2 = $config['maxcountall2']."人团";
		}
        if ($config['groupprice3']>0) {
            $gruoptips3 = $config['formtextcenter3'];
            $gruoptips3 = str_replace("#fee",'',$gruoptips3);
            $gruoptips3 = str_replace("#dan",'',$gruoptips3);
            $gruoptips3 = str_replace("#tuan",'',$gruoptips3);
            $gruoptips3 = str_replace("#br",'',$gruoptips3);
            $gruoptips3 = str_replace("￥",'',$gruoptips3);

            if (empty($config['formtextcenter2'])) {
                $gruoptips3 = $config['maxcountall2']."人团";
            }
        }
	}
		
if ($op2=="search") {
	$keyword = $_P['searchtxt'];
	if (!empty($keyword)) {
        if (intval($keyword)>10000 && intval($keyword)<30000) {
            $tempa = intval($keyword)-10000;
            $sql.= " and (r.pid = '". $tempa . "' or r.id = '". $tempa. "') ";
        } else {
			$sql .= " and (r.nickname like '%{$keyword}%' or r.username like '%{$keyword}%' or r.mobile like '%{$keyword}%' or r.option like '%{$keyword}%' or r.address like '%{$keyword}%' or r.datetime like '%{$keyword}%' or r.addinfo like '%{$keyword}%')";
        }
	}
}
	
	  //       $sql =  "SELECT COUNT(ord.id) FROM " . tablename ( t_record ) . " as ord WHERE  ord.pid = '{$row['id']}'";
		// $dtotal = (int)db_fetchcolumn ($sql);
$condition = $sql;

$total = (int)db_fetchcolumn ("SELECT count(r.id)  FROM " . tablename ( t_record ) . " as r
		left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid " . $condition ."
		order by r.addtime desc ");

$sql  = "SELECT r.*,w.username as workername FROM " . tablename ( t_record ) . " as r
		left join " . tablename ( t_worker ) . " as w on r.workerid = w.uid and r.themeid = w.themeid " . $condition ."
		order by r.addtime desc LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;


$orders  = db_select ( $sql);
$wlist = Worker::getworkerlist($system,$themeid);
if (!empty($orders)){
	foreach ($orders as $index => $item) {

		$fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$item['uid']));
		$orders[$index]['scansum']=$fans['scansum'];
		$orders[$index]['forward']=$fans['forward'];
        $orders[$index]['chongzhi']=$orders[$index]['chongzhi']=='0.00' && $fans['chongzhi']>0?$fans['chongzhi']:$orders[$index]['chongzhi'];;
        $orders[$index]['member_beizhu']=empty($orders[$index]['member_beizhu']) && !empty($fans['beizhu'])?$fans['beizhu']:$orders[$index]['member_beizhu'];;

		if(!empty($item['fromuid'])){
			$fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$item['fromuid']));
			if (!empty($fans['username'])){
				$orders[$index]['tjr']=$fans['username'];
			}elseif (!empty($fans['nickname'])){
				$orders[$index]['tjr']=$fans['nickname'];
			}else{
				$orders[$index]['tjr']=$item['fromuid'];
			}			
		}else{
			$orders[$index]['tjr']="无";
		}

		if ($system['fanpai']==1){
			$pm = array(":themeid"=>$themeid,":openid"=>$item['openid']);
			$yichou = (int)db_fetchcolumn("SELECT COUNT(*)  FROM ".tablename(t_fanpaichoujiang)."
			WHERE themeid = :themeid and openid = :openid",$pm);
			$list[$index]['fanpaichoujiang'] = $yichou;

			$jihui = $config['fanpailimit']- $yichou;
			$fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$item['uid']));
			$list[$index]['fanpaijihui'] =  ($jihui>$fans['jihui']) ? $fans['jihui'] : $jihui ;
		}

		if(!empty($item['workerid'])){
            $fans = Worker::getWokerName($system,$themeid,$item['workerid'],$wlist);
			$orders[$index]['workername'] = $fans['username'];
			$orders[$index]['teamname'] = $fans['teamname'];
			$orders[$index]['companyname'] = $fans['companyname'];

			if ($myworker['level'] ==3 || $myworker['level'] ==4){
		        $orders[$index]['workernameall'] = "电话：" . $item['mobile'];
			}else{
		        if ($system['is_multiple_merchants']){
		        	$txttemp = mb_substr($orders[$index]['companyname'],0,5,'utf-8') . "-";
		        }else{
		        	$txttemp = mb_substr($orders[$index]['teamname'],0,5,'utf-8') . "-";
		        }
		        $txttemp .= $orders[$index]['workername'];
		        $orders[$index]['workernameall'] = "销售：" . $txttemp;
		    }
		}
		
		if ($system['ruanjian']==0 && $system['softstyle']==5 && !empty($item['address'])) {
	        $itemdz = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= '" . $item['address']."'");
	        $xianname = $itemdz['areaName'];
	        if (!empty($itemdz)){
		        $itemdz = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $itemdz['parentId']);
		        $shiname = $itemdz['areaName'];
			}
			if (!empty($itemdz)){
	        $itemdz = db_find ( "SELECT * FROM " . tablename ( t_shengshi ) . " WHERE areaId= " . $itemdz['parentId']);
	        $shengname = $itemdz['areaName'];
	        }
	        $orders[$index]['address'] = $shengname . $shiname .$xianname;
	    }



	    $orders[$index]['sid'] = $total - ($pageNumber - 1) * $pageSize-$index;

	    $orders[$index]['addtime'] = date("Y-m-d H:i:s", $item['addtime']);
	    $orders[$index]['nickname'] = $item['nickname'];
	    if (empty($item['uid'])) {
	    	$orders[$index]['avatar'] = $_G['URL']['FCWORK_CSS'] . 'images/avatar1.jpg';
	    }else{
	    	$orders[$index]['avatar'] = tomedia($item['avatar']);
		}
        if ($item['status'] ==-2){
            $txttemp = "虚拟订单";
        }elseif ($item['status'] < 0){
        	if ($item['isrefund']==2) {
        		$txttemp = "自动退款";
        	} else {
        		$txttemp = "手工退款";
        	}
        }elseif ($item['status'] == 1){
            $txttemp = "已支付<span>￥<i>" . $item['fee'] . "</i></span>";
        }elseif ($item['status'] == 0){
            $txttemp = "未支付";
        }elseif ($item['status'] == 3){
            $txttemp = "线下定单";
        }
		$orders[$index]['statustxt'] = $txttemp;
        $txttemp='';
//		$orders[$index]['exampleurl'] = "/".createMobileUrl('w_example',array("themeid"=>$themeid,"id"=>$item['id']));
//		$orders[$index]['orderediturl'] = "/".createMobileUrl('w_orderedit',array("themeid"=>$themeid,"id"=>$item['id'],"uid"=>$item['uid']));
//		$orders[$index]['inputurl'] = "/".createMobileUrl('w_input',array("themeid"=>$themeid,"op"=>"bangding","recordid"=>$item['id']));

//        $txttemp = "<a href='" . $orders[$index]['orderediturl'] . "' class='changeBtn'>修改订单</a>";

//        if ($item['status'] == 3 && empty($item['openid'])){
//            $txttemp .= "    <a href='" . $orders[$index]['inputurl'] . "' class='checkBtn'>绑定微信</a>";
//        }elseif ($item['status'] == 1){
//            $txttemp .= "   <a href='" . $orders[$index]['exampleurl'] . "' class='checkBtn'>交易凭证</a>";
//        }
        if ($config['maxcount']>0 && $item['tuannum']>1) {
            $txttemp .= "   <a href='" ."/".createMobileUrl('w_group',array("themeid"=>$themeid,"op"=>'all',"pid"=>$item['pid'])) . "' class='checkBtn checkBtn3'>团成员</a>";
        }
        $orders[$index]['urltxt']  = $txttemp;

        //详细信息
        $txttemp = "";
        if ($myworker['level']!=3) {
        	$txttemp .= "<p>电话：{$item['mobile']}</p>";
        }
        if (!empty($config['address'])){
        	$txttemp .= "<p>{$config['address']}：{$item['address']}</p>";
        }
        if (!empty($config['shops'])){
        	$txttemp .= "<p>{$config['shops']}：{$item['option']}</p>";
        }
        if (!empty($config['datetime'])){
        	$txttemp .= "<p>{$config['datetime']}：{$item['datetime']}</p>";
        }
        if (!empty($config['addinfo'])){
        	$txttemp .= "<p>{$config['addinfo']}：{$item['addinfo']}</p>";
        }
        $txttemp .= "<p>浏览:{$orders[$index]['scansum']}次</p>";
        $txttemp .= "<p>转发:{$orders[$index]['forward']}次</p>";
        $txttemp .= "<p>推荐人:" .  mb_substr($orders[$index]['tjr'],0,12,'utf-8') . "</p>";

        if ($orders[$index]['is_member'] > 0){
            $member_from=array('未标记','老客户','新客户','微信转帐','店内付款');
            $orders[$index]['member_info']['isshow']=true;
            $orders[$index]['member_info']['is_member'] =$member_from[$orders[$index]['is_member']];
        }
        if ($orders[$index]['chongzhi'] > 0){
            $orders[$index]['member_info']['isshow']=true;
            $orders[$index]['member_info']['chongzhi'] = '【储值' . $orders[$index]['chongzhi']. '元】' ;
        }
        if (!empty($orders[$index]['member_beizhu'])){
            $orders[$index]['member_info']['isshow']=true;
            $orders[$index]['member_info']['member_beizhu'] = $orders[$index]['member_beizhu'] ;
        }

        if ($myworker['level']==3) {
			$txttemp .= "<p>销售:";
	        if ($system['is_multiple_merchants']){
	        	$txttemp .=mb_substr($orders[$index]['companyname'],0,8,'utf-8') . "-";
	        }
	        $txttemp .= $orders[$index]['teamname'] ."-" . $orders[$index]['workername']. "</p>";
        }

        if ($config['maxcount']>0){
        	$item['pid'] = $item['pid'] +1000;
        	$txttemp .= "<p>团号:" . $item['pid'] . "</p>";
        	$txttemp .= "<p>团人数:" . $item['tuannum'] . "人</p>";

            if ($item['isfinish']==1){
				$txttemp .= "<p>团状态:拼团成功</p>";
            }elseif ($item['xunifinish']==1){
				$txttemp .= "<p>团状态:虚拟成团</p>";
            }else{
				$txttemp .= "<p>团状态:拼团中</p>";
            }                                

	        if ($item['type']==0) {
        		$txttemp .= "<p>团身份:团长</p>";
	        }elseif ($item['type']==9) {
        		$txttemp .= "<p>团身份:单买</p>";
	        }else {
        		$txttemp .= "<p>团身份:团员</p>";
	        }
	        if (($config['groupprice2']>0 || $config['groupprice3']>0) && $item['type']!=9){
	        	if ($item['renshu']==1){
        			$txttemp .= "<p>团套餐:" . $gruoptips2 . "</p>";
        		}elseif ($item['renshu']==2){
                    $txttemp .= "<p>团套餐:" . $gruoptips3 . "</p>";
                }else{
        			$txttemp .= "<p>团套餐:" . $gruoptips . "</p>";
        		}
	        }
        }
        $orders[$index]['showtext']  = $txttemp;
	}
}
if ($_P['show']=='get') {
    $result=  array();
    $result['curPageData'] = $orders;
    $result['totalPage'] =  ceil($total / $pageSize)-1;
    $result['totalSize'] =  $total-$pageSize;

    if ($pageNumber*$pageSize>=$total) {
    	$result['hasNext'] = false ;
    }else{
    	$result['hasNext'] = true  ;
    }
	return_msg($result, '', 'ajax');
}else{
	$return_clicent = get_defined_vars();
return view('/fcworker/fc_order_agent' , $return_clicent);
}

}
}